<?
$now_date=date("l, F j, Y \a\\t g:i A",strtotime("-2 hours")).", GMT";
$dbh=$dbh81;
if (isset($_POST[hid_sub_var]) && $_POST[hid_sub_var]==415) {
        if (empty($_POST[total_price])) {
		$params[error_msg]=1;
		$params[sid] = $sid;
                $params[action] = "walletAccountRefill";
                $url = "$baseURL/$webDIR/?".encode_params($params);
		header("Location: $url");
                #$errorMsg=1;
		#$fileTemplate="walletAccountRefill.html";
                #include("main.html");
		exit();
	} elseif ($_POST[total_price]<'44') {
		$params[error_msg]=6;
                $params[sid] = $sid;
                $params[action] = "walletAccountRefill";
                $url = "$baseURL/$webDIR/?".encode_params($params);
                header("Location: $url");
                exit();
        } elseif (!empty($_POST[total_price]) && !preg_match("/^\d*$/", $_POST[total_price]) && !preg_match("/^\d*\.\d*$/",$_POST[total_price])) {
                $params[error_msg]=2;
		$params[sid] = $sid;
                $params[action] = "walletAccountRefill";
		$url = "$baseURL/$webDIR/?".encode_params($params);
                header("Location: $url");
		#$fileTemplate="walletAccountRefill.html";
                #include("main.html");
		exit();
        } else {
                $total_price=$_POST[total_price];
                $reseller[reseller_id]=$id;
                $reseller[username]=$username;
                $reseller[action]='wallet';
                $reseller[temp_state]='begin';
		$query="SELECT * FROM wallet WHERE reseller_id='$id' and currency='$_POST[currency]'";
		$pg_res=pg_query($dbh81,$query);
		//$current_balance=pg_fetch_result($pg_res,0,'amount');
		$num=pg_num_rows($pg_res);
		if ($num==0) {
			$current_balance=0;
		} else {
			$current_balance=pg_fetch_result($pg_res,0,'amount');
		}
                if (!empty($_POST[code])) {
                        //------------------------------------------------------
                                $sql['type']='SELECT';
                                $sql['params']='id,sum,currency';
                                $sql['table']='wallet_coupons';
                                $sql['where']="reseller_id='$id' AND code='$code' AND usage_count!='0'";
                                $sql['options']='ORDER BY currency ASC';
                                $sql['return']='struct';
                        //------------------------------------------------------
                        if (!$result=sql_exec($sql,$dbh81)) {
                                $params[error_msg]=3;
				$params[sid] = $sid;
		                $params[action] = "walletAccountRefill";
		                $url = "$baseURL/$webDIR/?".encode_params($params);
		                header("Location: $url");
				#$fileTemplate="walletAccountRefill.html";
                		#include("main.html");
                		exit();
                        } else {
                                $c_id=$result[0][id];
                                $c_sum=$result[0][sum];
                                $c_curr=$result[0][currency];
                                if ($c_curr!=$currency) {
                                        $params[error_msg]=4;
					$params[sid] = $sid;
                                	$params[action] = "walletAccountRefill";
                                	$url = "$baseURL/$webDIR/?".encode_params($params);
                                	header("Location: $url");
					#$fileTemplate="walletAccountRefill.html";
                                	#include("main.html");
                                	exit();
                                } else {
                                        $new_sum=$total_price+$c_sum;
					if ($num==0) {
						$reseller[resellers][]="INSERT INTO wallet VALUES('$id','$new_sum','$currency','f')";
					} else  {
                                        	$reseller[resellers][]="UPDATE wallet SET amount=amount+'$new_sum'
                                        	                        WHERE reseller_id='$id'
                                        	                        AND currency='$currency'";
					}
                                        $reseller[resellers][]="INSERT INTO wallet_history (status, reseller_id, amount,
                                                                currency, order_date, comment, paytype, init_amount)
                                                                VALUES('available','$id','$new_sum',
                                                                '$currency',now(),'credit card','card',
                                                                '$total_price')";
                                        $reseller[resellers][]="UPDATE wallet_coupons SET used='t', usage_count=usage_count-1
                                                                WHERE id='$c_id'";
                                        $reseller[resellers][]="INSERT INTO wallet_coupons_usage (coupon_id,used_on)
                                                                VALUES('$c_id',now())";
                                }
                        }
                } else {
                	# primerna sistemka za dobawyane na bonusi. zadylzhitelno tryabva da
                	#syshtestvuva $total_price za da se znae kolko pari e vyvel klienta
                	#(pri eventualen refund da ne mu se vryshta sumata+bonusa)..

                	#if ($total_price > 100 && $total_price <= 500) {
                	#       $new_sum=$total_price+'10';
                	#} elseif ($total_price > 500 && $total_price <= 1000) {
                	#       $new_sum=$total_price+'20';
                	#} else {
                	#        $new_sum=$total_price;
                	#}

			//------------------------------------------------------
		           $sql['type']='SELECT';
		           $sql['params']='*';
		           $sql['table']='wallet_additions';
		           $sql['where']="";
		           $sql['options']='';
		           $sql['return']='struct';
		        //------------------------------------------------------
		        if (!$result=sql_exec($sql,$dbh81,'assoc')) {
			   $params[error_msg]=3;
			   $params[sid] = $sid;
                           $params[action] = "walletAccountRefill";
                           $url = "$baseURL/$webDIR/?".encode_params($params);
                           header("Location: $url");
                           #$fileTemplate="walletAccountRefill.html";
                           #include("main.html");
                           exit();
		        }
		        foreach ($result as $value) {
		                if ($total_price>=$value[a_init] && $total_price<=$value[a_end]) {
		                        $plus=$value[percent];
	                	}
        		}
		        if ($plus!=0) {
		                $po=$total_price*$plus/100;
		        } else {
		                $po=0;
		        }
		        $new_sum=$total_price+$po;

			if ($num==0) {
				$reseller[resellers][]="INSERT INTO wallet VALUES('$id','$new_sum','$currency','f')";
			} else {
                		$reseller[resellers][]="UPDATE wallet SET amount=amount+'$new_sum'
                		                      WHERE reseller_id='$id'
                		                      AND currency='$currency'";
			}
                	$reseller[resellers][]="INSERT INTO wallet_history (status, reseller_id, amount,
                	                      currency, order_date, comment, paytype, init_amount)
                	                      VALUES('available','$id','$new_sum',
                	                      '$currency',now(),'credit card','card',
                	                      '$total_price')";
			$reseller[resellers][]="UPDATE wallet_settings SET mail_sent=false WHERE reseller_id='$id'";
                }
		$params[sid] = $sid;
                $params[action] = "walletAccountRefill";
                $url = "$baseURL/$webDIR/?".encode_params($params);

                $reseller[return_url] = $url;

                $reseller[sales][0]['name']='wallet';
                $reseller[sales][0]['amount_total']=$total_price;
                $reseller[sales][0]['amount_wholesale']=$total_price;
                $reseller[sales][0]['currency']="USD";
                $reseller[sales][0]['type']="wallet_refill";
		$reseller[sales][0]['purchase_action']='none';

                //------------------------------------------------------
                $sql['type']='SELECT';
                $sql['params']='name, first_name, last_name, email';
                $sql['table']='resellers';
                $sql['where']="reseller_id='$id'";
                $sql['options']='';
                $sql['return']='struct';
                //------------------------------------------------------
                if (!$result=sql_exec($sql,$dbh81)) {
                     $params[error_msg]=5;
		     $params[sid] = $sid;
                     $params[action] = "walletAccountRefill";
                     $url = "$baseURL/$webDIR/?".encode_params($params);
                     header("Location: $url");
		     #$fileTemplate="walletAccountRefill.html";
                     #include("main.html");
                     exit();
		}
                $fullname=$result[0][first_name]." ".$result[0][last_name];
		$reseller[email]=$result[0][email];
		$nick_name=$result[0][name];

		//------------------------------------------------------
                $sql['type']='SELECT';
                $sql['params']='max(temporary_id)+1 as max';
                $sql['table']='temporary';
                $sql['where']="";
                $sql['options']='';
                $sql['return']='struct';
                //------------------------------------------------------
                if (!$result=sql_exec($sql,$dbh81)) {
                     $params[error_msg]=5;
                     $params[sid] = $sid;
                     $params[action] = "walletAccountRefill";
                     $url = "$baseURL/$webDIR/?".encode_params($params);
                     header("Location: $url");
                     exit();
                }
		$track=$result[0][max];
		$new_balance=$current_balance+$new_sum;

                $SETTINGS["baseTMName"]="ResellersPanel Team";
                $SETTINGS["baseSupportEmail"]="support@resellerspanel.com";

                $mail_array= getMail ("wallet_refill", Array(
                                "fullname"=>$fullname,
                                "percent"=>$plus,
                                "addition"=>$po,
                                "new_sum"=>$new_sum,
                                "total_price"=>$total_price,
                                "current_balance"=>$new_balance,
                                "tracking_id"=>$track,
                                "username"=>$nick_name,
                                "date"=>$now_date,
                                "mainserver" => "ResellersPanel"
                                ), Array("HEADER"=>1,"BODY"=>1,"FOOTER"=>1), "resellers_id", $id,'mail');

                $reseller[email_notification][from]= $mail_array[from];
                $reseller[email_notification][mime]= $mail_array[mime];
                $reseller[email_notification][subject]= $mail_array[subject];
                $reseller[email_notification][body]=$mail_array[body];
		if ($_POST['processor'] == '') {
			//$reseller[payment_method]='2co';
			//if (is_me()) {
				$reseller['payment_method'] = 'worldpay';
        // patch for the correct autologin after payment
        $reseller['return_url'] = $baseURL.'/'.$webDIR.'/?sid='.$sid.'&action=walletAccountRefill';
			//}
		} elseif ($_POST[processor]=='paypal') {
			$reseller[payment_method]='paypal';
		} else {
					 $errorMsg = translate('int_error');
					 include_once('errorMsg.html');
					 exit;
//			exit("ERROR - Payment mismatch!");
		}

		$reseller[payment_exchange]=1;
		$reseller[payment_currency]='USD';

		if ($_SERVER[REMOTE_ADDR]=='213.222.51.231') {
			echo "$current_balance<br>";
			echo "$new_sum<br>";
			echo "$total_price<br>";
                	echo "<pre>";
                	print_r($reseller);
                	echo "</pre>";
                	exit();
		}
                $temporary_id=add_temporary($reseller);

		if ($reseller['payment_method'] == 'worldpay') {
			include('../rp2/gotopay_wp.php');
		} else {
                	include('../rp2/gotopay.php');
		}

        }

}

?>
